package com.dyava.commons.lock.complex;

import com.dyava.commons.lock.KeyLock;
import java.util.List;

public class ComplexKeyLock implements KeyLock{
    List<KeyLock> keyLockList ;

    public List<KeyLock> getKeyLockList() {
        return keyLockList;
    }

    public void setKeyLockList(List<KeyLock> keyLockList) {
        this.keyLockList = keyLockList;
    }

    public ComplexKeyLock(){

    }

    public ComplexKeyLock(List<KeyLock> keyLockList) {
        this.keyLockList = keyLockList;
    }


    @Override
    public boolean tryLock() {
        boolean res=false;
        if(keyLockList != null){
            for(KeyLock keyLock : keyLockList){
                res = keyLock.tryLock();
                if(!res){
                    return false;
                }
            }
        }
        return res;
    }

    @Override
    public void lock(int maxWaitTime) {
        if(keyLockList != null) {
            for (KeyLock keyLock : keyLockList) {
                keyLock.lock(maxWaitTime);
            }
        }
    }

    @Override
    public void close() {
        if(keyLockList != null) {
            int i = keyLockList.size()-1;
            for(;i>=0;i--){
                KeyLock keyLock = keyLockList.get(i);
                keyLock.close();
            }
        }
    }
}
